<template>
  <ele-modal :form="true" :width="800" :title="data ? '编辑菜单' : '新增菜单'" position="center" v-model="visible"
    @open="handelOpen" @close="handelClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
      <el-row :gutter="24">
        <!-- 上级 -->
        <el-col :lg="12" :md="12" :sm="12" :xs="24">
          <el-form-item label="上级目录:" prop="parentId">
            <el-tree-select ref="treeRef" clearable :check-strictly='true' v-model="form.parentId" :data="menuTree"
              highlight-current node-key="id" :props="{ label: 'name' }" :expand-on-click-node="false" />
          </el-form-item>
        </el-col>
        <!-- 菜单名称 -->
        <el-col :lg="12" :md="12" :sm="12" :xs="24">
          <el-form-item label="菜单名称:" prop="name">
            <el-input v-model.trim="form.name" clearable></el-input>
          </el-form-item>
        </el-col>
        <!-- 菜单类型 -->
        <el-col :lg="12" :md="12" :sm="12" :xs="24">
          <el-form-item label="菜单类型:" prop="type">
            <el-radio-group v-model="form.type" @change="typeChange">
              <el-radio value="0">目录</el-radio>
              <el-radio value="1">菜单</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!-- 组件类型 -->
        <el-col :lg="12" :md="12" :sm="12" :xs="24">
          <el-form-item v-if="form.type == '1'" label="组件类型:" prop=" componentType">
            <el-radio-group v-model="form.componentType">
              <el-radio :value="'0'">组件</el-radio>
              <el-radio :value="'1'">内链</el-radio>
              <el-radio :value="'2'">外链</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!-- 组件地址||链接地址 -->
        <el-col :lg="12" :md="12" :sm="12" :xs="24">
          <el-form-item :label="form.componentType == '0' ? '组件地址:' : '链接地址:'" prop="componentPath">
            <el-input :disabled="form.type == '0'" v-model.trim="form.componentPath" clearable></el-input>
          </el-form-item>
        </el-col>
        <!-- 状态 -->
        <el-col :lg="12" :md="12" :sm="12" :xs="24">
          <el-form-item label="菜单状态:" prop="status">
            <el-switch v-model="form.status" class="ml-2" inline-prompt
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="启用" inactive-text="禁用"
              active-value="1" inactive-value="0" />
          </el-form-item>
        </el-col>
        <!-- 路由地址 -->
        <el-col :lg="12" :md="12" :sm="12" :xs="24">
          <el-form-item label="路由地址:" prop="path">
            <el-input v-model.trim="form.path" clearable></el-input>
          </el-form-item>
        </el-col>
        <!-- 菜单图标 -->
        <el-col :lg="12" :md="12" :sm="12" :xs="24">
          <el-form-item label="菜单图标" prop="icon">
            <ele-icon-select clearable filterable :data="icons" v-model="form.icon" placeholder="请选择图标">
              <template #icon="{ icon }">
                <el-icon szie="small">
                  <component :is="icon" />
                </el-icon>
              </template>
            </ele-icon-select>
          </el-form-item>
        </el-col>
        <!-- 缓存页面 -->
        <el-col :lg="8" :md="12" :sm="12" :xs="24">
          <el-form-item label="缓存页面:" prop="keepAlive">
            <el-switch v-model="form.keepAlive" class="ml-2" inline-prompt
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="启用" inactive-text="禁用"
              active-value="1" inactive-value="0" />
          </el-form-item>
        </el-col>
        <!-- 是否隐藏 -->
        <el-col :lg="8" :md="8" :sm="12" :xs="24">
          <el-form-item label="是否隐藏:" prop="hide">
            <el-switch v-model="form.hide" class="ml-2" inline-prompt
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="是" inactive-text="否"
              active-value="1" inactive-value="0" />
          </el-form-item>
        </el-col>
        <!-- 排序 -->
        <el-col :lg="8" :md="12" :sm="12" :xs="24">
          <el-form-item label="排序:" prop="sort">
            <el-input-number v-model="form.sort" :min="0" :value-on-clear="0" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" :loading="loading" @click="save">提交</el-button>
    </template>
  </ele-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue"
import { EleMessage } from "ele-admin-plus";
import type { FormInstance, FormRules } from 'element-plus';
import { useFormData } from "@/utils/use-form-data";
import { add, edit } from "@/api/system/SysMenu"
import type { SysMenu, AddSysMenu } from "@/api/system/SysMenu/model"
import { getIconData } from "@/components/IconSelect/util";

const props = defineProps<{
  currentNode: SysMenu | null
  data: SysMenu | null
  menuTree: SysMenu[]
}>()

const emit = defineEmits<{
  (e: 'reload'): void
}>()

const formRef = ref<FormInstance | null>(null);
const visible = defineModel({ type: Boolean });
const loading = ref<boolean>(false)
const icons = computed((): string[] => {
  const icons = Object.keys(getIconData()).filter((name) =>
    name.startsWith('IconPro')
  );
  return icons.filter((name) => !name.endsWith('Filled'))
})
const { form, resetFields, assignFields } = useFormData<AddSysMenu>({
  parentId: '',               // 上级ID，默认为一级菜单
  name: '',                    // 菜单名称
  type: '0',                   // 菜单类型：0目录 1菜单
  componentType: '0',          // 修改：确保初始值为字符串类型
  componentPath: "",           // 组件路径（可选）
  status: '1',                 // 状态：1正常，0禁用
  path: '',                    // 路由地址
  icon: "",                  // 图标（可选）
  keepAlive: '0',              // 缓存页面：0禁用 1启用
  hide: '0',                   // 是否隐藏（可选）
  meta: null,                  // 其他路由元信息（可选）
  sort: 0,                     // 排序序号
})

const rules = reactive<FormRules>({
  name: [
    {
      required: true,
      message: '请输入菜单名称',
      type: 'string',
      trigger: 'blur'
    }
  ],
  path: [
    {
      required: true,
      message: '请输入路由地址名称',
      type: 'string',
      trigger: 'blur'
    }
  ],
  componentPath: [
    {
      required: form.type != '0',
      message: '请输入地址',
      type: 'string',
      trigger: 'blur'
    }
  ]
});

const typeChange = (val: string) => {
  if (val == '0') {
    form.componentPath = null
  }
}

const save = () => {
  formRef.value!.validate()
    .then(async () => {
      loading.value = true
      form.parentId = form.parentId ? form.parentId : '0'
      const res = props.data ? await edit({ id: props.data.id, ...form, pathCode: props.data.pathCode, level: props.data.level }) : await add({ ...form })
      loading.value = false
      if (res.code == 200) {
        EleMessage.success('成功提交')
        emit('reload')
      } else {
        EleMessage.error(res.message)
        return
      }
      visible.value = false
    })


}

const handelOpen = () => {
  if (props.data) {
    assignFields(props.data)
    form.parentId = props.data.parentId == '0' ? '' : props.data.parentId
    console.log(form)
  } else {
    form.parentId = props.currentNode ? props.currentNode.id : ''
  }
}

const handelClose = () => {
  resetFields()
  formRef.value?.resetFields()
}

</script>

<style scoped></style>
